package dxlateplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class GetUserLatePlatesServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(GetUserLatePlatesServlet.class.getName());

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

        String userName = req.getParameter("userName");

        PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + LatePlate.class.getName() + " order by value asc";
        List<LatePlate> latePlateList = (List<LatePlate>) pm.newQuery(query).execute();
        ArrayList<LatePlate> resultList = new ArrayList<LatePlate>();


        if(userName != null) {
            for(LatePlate plate: latePlateList) {
                if((plate.getUserName() != null) && plate.getUserName().equalsIgnoreCase(userName)) {
                    resultList.add(plate);
                }
            }
        }
        pm.close();

        if(resultList.size() > 0) {
            String json = new Gson().toJson(resultList);
            resp.getWriter().print(json);
        }

    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
        doGet(req, resp);
    }
}
